package com.itheima.controller;

import com.itheima.pojo.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 回话跟踪方案 Cookie Session
 */
@Slf4j
@RestController
public class SessionController {
    /**
     * 设置 Cookie
     * @param response
     * @return
     */
    @GetMapping("/c1")
    public Result cookie1(HttpServletResponse response){
        response.addCookie(new Cookie("username","junming"));
        return Result.success();
    }
    /**
     * 获取cookie
     *
     */
    @GetMapping("/c2")
    public Result cookie1(HttpServletRequest request){
        Cookie[] cookies= request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("username")){
                System.out.println("usrename:"+cookie.getValue());
            }
        }
        return Result.success();
    }


    // 设置 session
    @GetMapping("/s1")
    public Result session1(HttpSession session){
        log.info("HttpSession-s1:{}",session.hashCode());
        session.setAttribute("loginUser","junming");
        return  Result.success();
    }
    // 获取Session
    @GetMapping("/s2")
    public Result session2(HttpServletRequest request){
            HttpSession session = request.getSession();
            log.info("HttpSession-s2:{}",session.hashCode());
            // 从session中获取数据
            Object loginUser= session.getAttribute("loginUser");
            log.info("loginUser:{}",loginUser);
            return Result.success();
    }



}
